package cn.schoolwow.quickflow.service.executor.business;

import cn.schoolwow.quickflow.QuickFlowExecutor;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.domain.FlowExecutorConfig;
import cn.schoolwow.quickflow.executor.QuickFlowExecutorInner;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.quickflow.flow.CompositeBusinessFlow;
import cn.schoolwow.quickflow.listener.SingleFlowListener;
import cn.schoolwow.quickflow.listener.TryCatchFinallyHandler;
import cn.schoolwow.quickflow.util.QuickFlowUtil;

public class QuickFlowExecutorBusinessOperationImpl implements QuickFlowExecutorBusinessOperation{
    private FlowExecutorConfig flowExecutorConfig;

    public QuickFlowExecutorBusinessOperationImpl(FlowExecutorConfig flowExecutorConfig) {
        this.flowExecutorConfig = flowExecutorConfig;
    }

    @Override
    public QuickFlowExecutor next(String flowName) {
        if(null==flowExecutorConfig.flowExecutorRootConfig.flowConfig.flowConfigHandlerContext.flowMappingHandler){
            throw new IllegalArgumentException("请先指定流程名称实例映射处理器!");
        }
        BusinessFlow flow = flowExecutorConfig.flowExecutorRootConfig.flowConfig.flowConfigHandlerContext.flowMappingHandler.getFlow(flowName);
        if(null==flow){
            CompositeBusinessFlow compositeBusinessFlow = flowExecutorConfig.flowExecutorRootConfig.flowConfig.flowConfigHandlerContext.flowMappingHandler.getCompositeBusinessFlow(flowName);
            if(null==compositeBusinessFlow){
                throw new IllegalArgumentException("根据流程名称查找流程示例失败!流程名称:"+flowName);
            }
            next(compositeBusinessFlow);
        }else{
            flowExecutorConfig.flowList.add(flow);
        }
        return flowExecutorConfig.quickFlowExecutor;
    }

    @Override
    public QuickFlowExecutor next(BusinessFlow flow) {
        flowExecutorConfig.flowList.add(flow);
        return flowExecutorConfig.quickFlowExecutor;
    }

    @Override
    public QuickFlowExecutor next(CompositeBusinessFlow compositeBusinessFlow) {
        BusinessFlow businessFlow = QuickFlowUtil.getBusinessFlow(compositeBusinessFlow);
        flowExecutorConfig.flowList.add(businessFlow);
        return flowExecutorConfig.quickFlowExecutor;
    }

    @Override
    public QuickFlowExecutor singleFlowListener(SingleFlowListener singleFlowListener) {
        flowExecutorConfig.singleFlowListener = singleFlowListener;
        return flowExecutorConfig.quickFlowExecutor;
    }

    @Override
    public QuickFlowExecutor tryCatchFinallyHandler(TryCatchFinallyHandler tryCatchFinallyHandler) {
        flowExecutorConfig.tryCatchFinallyHandler = tryCatchFinallyHandler;
        return flowExecutorConfig.quickFlowExecutor;
    }

    @Override
    public FlowContext execute() {
        QuickFlowExecutorInner quickFlowExecutorInner = new QuickFlowExecutorInner(flowExecutorConfig);
        return quickFlowExecutorInner.doExecute();
    }
}
